﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using RBAC.API.Command.Permission;
using RBAC.API.DTOs;

namespace RBAC.API.Handler.Permission
{
    public class PermissionGetHandler:IRequestHandler<PermissionGetCommand,ApiResult<List< PermissionDTO>>>
    {
        private readonly IRepository<PermissionModel> permissionway;
        private readonly IMapper mapper;
        private readonly ILogger<PermissionGetHandler> log;

        public PermissionGetHandler(IRepository<PermissionModel> permissionway, IMapper mapper, ILogger<PermissionGetHandler> log )
        {
            this.permissionway = permissionway;
            this.mapper = mapper;
            this.log = log;
        }
        /// <summary>
        /// 权限数据获取
        /// </summary>
        /// <param name="request">权限名称</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public Task<ApiResult<List<PermissionDTO>>> Handle(PermissionGetCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List< PermissionDTO>> res = new ApiResult<List<  PermissionDTO>>();
            var value = permissionway.GetAll().Where(x => x.IsDel == false);
            if(!string.IsNullOrEmpty(request.PermissionName))
            {
                value = value.Where(x => x.PermissionName.Contains(request.PermissionName));
            }
            var result= mapper.Map<List<PermissionDTO>>(value);
            if (result.Any())
            {
                res.Message = "成功获取权限数据";
                res.Code = StateCode.OK;
                res.Data = result ;
            }
            else
            {
                res.Message = "获取权限数据失败";
                res.Code = StateCode.Fail;
            }
            return Task.FromResult(res);
        }
    }
}
